//
//  WJYPalyMusicViewController.m
//  MooMusic
//
//  Created by wjy on 15/10/29.
//  Copyright © 2015年 wjy. All rights reserved.
//

#import "WJYPalyMusicViewController.h"
#import "PlayMusicHeaderView.h"
#import "LTY_TenSongsModel.h"
@interface WJYPalyMusicViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) PlayMusicHeaderView *headerView;
//播放圆盘, 滑条, 3个按钮. 收藏按钮
@property (nonatomic, strong) UIView *viewRound;
@property (nonatomic, strong) UISlider *slider;
@property (nonatomic, strong) UIButton *buttonPlay;
@property (nonatomic, strong) UIButton *buttonBack;
@property (nonatomic, strong) UIButton *buttonNext;
@property (nonatomic, strong) UIButton *buttonCollect;

//下面两个按钮, 切换页
@property (nonatomic, strong) UIButton *buttonCut;
@property (nonatomic, strong) UIButton *buttonList;

@property (nonatomic, strong) UIView *cutView;
@property (nonatomic, strong) UIButton *dqxhButton;
@property (nonatomic, strong) UIButton *qxhButton;
@property (nonatomic, strong) UIButton *sjButton;

@property (nonatomic, strong) UIView *listView;
@property (nonatomic, strong) UITableView *table;
@property (nonatomic, strong) UIButton *closeButton;

@property (nonatomic, strong)TabBarController *tabBarSingle;

//圆盘
@property (nonatomic ,strong) UIImageView *img;

//动画
@property (nonatomic, strong) CABasicAnimation *anima;


@end

@implementation WJYPalyMusicViewController

- (void)loadView
{
    [super loadView];
    self.tabBarSingle = [TabBarController shareTabBar];
    //定时器
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor blackColor];
    
    //KVO
    //    self.isCutMusic = [[NSUserDefaults standardUserDefaults] integerForKey:@"playType"];
    //    [self addObserver:self forKeyPath:@"isCutMusic" options:(NSKeyValueObservingOptionNew) context:nil];
    
    
    UIImageView *backImg = [[UIImageView alloc] initWithFrame:self.view.bounds];
    backImg.alpha = 0.6;
    backImg.image = [UIImage imageNamed:@"back3.jpg"];
    [self.view addSubview:backImg];

    
    [self backButton];
    [self create];
    
    
    
    //动画
    //    self.isplaybool = YES;
    //    self.stopAngle = 10;
    [self startAnimation];
    
}

#pragma mark - KVO
//- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
//{
//    if ([keyPath isEqualToString:@"isCutMusic"]) {
//        [[NSUserDefaults standardUserDefaults] setInteger:self.isCutMusic forKey:@"playType"];
//    }
//}

- (void)backButton
{
    self.headerView = [[PlayMusicHeaderView alloc] initWithFrame:CGRectMake(0, 20, SCREENWIDTH, 64)];
    self.headerView.backgroundColor = [UIColor clearColor];
    
    self.headerView.label.text = self.songTitle;
    [self.headerView.button addTarget:self action:@selector(back) forControlEvents:(UIControlEventTouchUpInside)];
    
    
    [self.view addSubview:self.headerView];

    
    
}
- (void)back
{
    [self.delegate sendIsCutMusic:self.isCutMusic];
    
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

#pragma mark - 创建圆盘
- (void)create
{
    self.viewRound = [[UIView alloc] initWithFrame:CGRectMake(SCREENWIDTH / 4.0, SCREENHEIGHT / 4.0, SCREENWIDTH / 2.0, SCREENWIDTH / 2.0)];
    self.viewRound.backgroundColor = [UIColor blackColor];
    self.img = [[UIImageView alloc] initWithFrame:self.viewRound.bounds];
    
    if (self.imgName == nil) {
        
        self.img.image = [UIImage imageNamed:@"back1.jpg"];
    } else {
        [self.img sd_setImageWithURL:[NSURL URLWithString:self.imgName]];
    }
    
    [self.viewRound addSubview:self.img];

    
    self.viewRound.layer.cornerRadius = SCREENWIDTH / 4.0;
    self.viewRound.clipsToBounds = YES;
    
    [self.view addSubview:self.viewRound];

    
    UIImage *img = [UIImage imageNamed:@"slider"];
    self.slider = [[UISlider alloc] initWithFrame:CGRectMake(SCREENWIDTH / 8.0 + 10, SCREENHEIGHT / 2.0 + 60, SCREENWIDTH / 8.0 * 6 - 20, 30)];
    //进度条样式
    //    [self.slider setMinimumTrackImage:img forState:UIControlStateNormal];
    //    [self.slider setMaximumTrackImage:img forState:UIControlStateNormal];
    //滑块样式
    [self.slider setThumbImage:img forState:UIControlStateHighlighted];
    [self.slider setThumbImage:img forState:UIControlStateNormal];
    [self.view addSubview:self.slider];
    [self.slider addTarget:self action:@selector(sliderAction:) forControlEvents:(UIControlEventValueChanged)];

    
    //放歌时间label
    self.start = [[UILabel alloc] initWithFrame:CGRectMake(40, self.slider.frame.origin.y + self.slider.frame.size.height + 10, 60, 30)];
    self.start.backgroundColor = [UIColor clearColor];
    self.start.textColor = [UIColor whiteColor];
    self.start.textAlignment = NSTextAlignmentCenter;
    self.start.font = [UIFont systemFontOfSize:15];
    [self.view addSubview:self.start];

    
    self.end = [[UILabel alloc] initWithFrame:CGRectMake(SCREENWIDTH - 45 - 60, self.slider.frame.origin.y + self.slider.frame.size.height + 10, 60, 30)];
    self.end.backgroundColor = [UIColor clearColor];
    self.end.textColor = [UIColor whiteColor];
    self.end.textAlignment = NSTextAlignmentRight;
    self.end.font = [UIFont systemFontOfSize:15];
    [self.view addSubview:self.end];
    
    //    NSInteger str1 = [[[self.tabBarSingle.array[self.tabBarSingle.index] urlList].firstObject objectForKey:@"duration"] integerValue];
    //    self.end.text = [NSString stringWithFormat:@"%.0f:%02ld", str1 / 1000 / 60.0, str1 / 1000 % 60];

    
    //3个button
    self.buttonBack = [UIButton buttonWithType:(UIButtonTypeCustom)];
    self.buttonBack.frame = CGRectMake(SCREENWIDTH / 4.0 - 20, SCREENHEIGHT / 2.0 + 180, 40, 40);
    [self.buttonBack setImage:[UIImage imageNamed:@"shangyiqu"] forState:(UIControlStateNormal)];
//        self.buttonBack.backgroundColor = [UIColor yellowColor];
    [self.view addSubview:self.buttonBack];
    [self.buttonBack addTarget:self action:@selector(backplay) forControlEvents:(UIControlEventTouchUpInside)];
    
    self.buttonPlay = [UIButton buttonWithType:(UIButtonTypeCustom)];
    self.buttonPlay.frame = CGRectMake(SCREENWIDTH / 2.0 - 30, SCREENHEIGHT / 2.0 - 10 + 180, 60, 60);
    [self.buttonPlay setImage:[UIImage imageNamed:self.buttonImg] forState:(UIControlStateNormal)];
    //    self.buttonPlay.backgroundColor = [UIColor yellowColor];
    [self.view addSubview:self.buttonPlay];
    [self.buttonPlay addTarget:self action:@selector(isplay) forControlEvents:(UIControlEventTouchUpInside)];
    
    self.buttonNext = [UIButton buttonWithType:(UIButtonTypeCustom)];
    self.buttonNext.frame = CGRectMake(SCREENWIDTH / 4.0 * 3 - 20, SCREENHEIGHT / 2.0 + 180, 40, 40);
    [self.buttonNext setImage:[UIImage imageNamed:@"xiayiqu"] forState:(UIControlStateNormal)];
    //    self.buttonNext.backgroundColor = [UIColor yellowColor];
    [self.view addSubview:self.buttonNext];
    [self.buttonNext addTarget:self action:@selector(nextplay) forControlEvents:(UIControlEventTouchUpInside)];
    
    //下面两个button
    self.buttonCut = [UIButton buttonWithType:(UIButtonTypeCustom)];
    self.buttonCut.frame = CGRectMake(self.buttonBack.frame.origin.x + 40 + 5, self.buttonBack.frame.origin.y + 40 + 20, 40, 40);
    if (self.isCutMusic == 0) {
        [self.buttonCut setImage:[UIImage imageNamed:@"quanxunhuan"] forState:(UIControlStateNormal)];
    } else if (self.isCutMusic == 1) {
        [self.buttonCut setImage:[UIImage imageNamed:@"danquxunhuan"] forState:(UIControlStateNormal)];
    } else if (self.isCutMusic == 2) {
        [self.buttonCut setImage:[UIImage imageNamed:@"suijibofang"] forState:(UIControlStateNormal)];
    }
    
    //    self.buttonBack.backgroundColor = [UIColor yellowColor];
    [self.view addSubview:self.buttonCut];
    [self.buttonCut addTarget:self action:@selector(choose) forControlEvents:(UIControlEventTouchUpInside)];
    
    self.buttonList = [UIButton buttonWithType:(UIButtonTypeCustom)];
    self.buttonList.frame = CGRectMake(self.buttonNext.frame.origin.x - 40 - 5, self.buttonBack.frame.origin.y + 40 + 20, 40, 40);
    [self.buttonList setImage:[UIImage imageNamed:@"liebiao"] forState:(UIControlStateNormal)];
    //    self.buttonBack.backgroundColor = [UIColor yellowColor];
    [self.view addSubview:self.buttonList];
    [self.buttonList addTarget:self action:@selector(musicList) forControlEvents:(UIControlEventTouchUpInside)];
    
    //切换播放模式的view
    self.cutView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREENHEIGHT, SCREENWIDTH, 100)];
    [self.view addSubview:self.cutView];
    self.cutView.layer.borderWidth = 1;
    self.cutView.layer.borderColor = [GrayColor CGColor];
    self.cutView.layer.cornerRadius = 10;
    self.cutView.clipsToBounds = YES;
    self.cutView.backgroundColor = [UIColor blackColor];

    
    
    
    self.dqxhButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    self.dqxhButton.frame = CGRectMake(50, 30, (SCREENWIDTH - 120) / 3.0, 40);
    [self.dqxhButton setImage:[UIImage imageNamed:@"danquxunhuan"] forState:(UIControlStateNormal)];
    //    self.buttonBack.backgroundColor = [UIColor yellowColor];
    [self.cutView addSubview:self.dqxhButton];
    [self.dqxhButton addTarget:self action:@selector(dqxhAction) forControlEvents:(UIControlEventTouchUpInside)];
    
    self.qxhButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    self.qxhButton.frame = CGRectMake((SCREENWIDTH - 120) / 3.0 + 50 + 10, 30, (SCREENWIDTH - 120) / 3.0, 40);
    [self.qxhButton setImage:[UIImage imageNamed:@"quanxunhuan"] forState:(UIControlStateNormal)];
    //    self.buttonBack.backgroundColor = [UIColor yellowColor];
    [self.cutView addSubview:self.qxhButton];
    [self.qxhButton addTarget:self action:@selector(qxhAction) forControlEvents:(UIControlEventTouchUpInside)];
    
    self.sjButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    self.sjButton.frame = CGRectMake(SCREENWIDTH - 50 - (SCREENWIDTH - 120) / 3.0, 30, (SCREENWIDTH - 120) / 3.0, 40);
    [self.sjButton setImage:[UIImage imageNamed:@"suijibofang"] forState:(UIControlStateNormal)];
    //    self.buttonBack.backgroundColor = [UIColor yellowColor];
    [self.cutView addSubview:self.sjButton];
    [self.sjButton addTarget:self action:@selector(sjAction) forControlEvents:(UIControlEventTouchUpInside)];
    
    //播放歌曲列表
    self.listView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREENHEIGHT, SCREENWIDTH, SCREENHEIGHT / 2.0)];
    self.listView.backgroundColor = [UIColor clearColor];
    //    self.listView.alpha = 0.3;
    [self.view addSubview:self.listView];
    
    UIVisualEffectView *mao = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:(UIBlurEffectStyleLight)]];
    mao.frame = self.listView.bounds;
    [self.listView addSubview:mao];

    
    self.closeButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    self.closeButton.frame = CGRectMake(0, self.listView.bounds.size.height - 40, SCREENWIDTH, 40);
    self.closeButton.backgroundColor = [UIColor blackColor];
    [self.closeButton setTitle:@"关 闭" forState:(UIControlStateNormal)];
    [self.closeButton setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    [self.listView addSubview:self.closeButton];
    [self.closeButton addTarget:self action:@selector(closeListView) forControlEvents:(UIControlEventTouchUpInside)];
    
    [self createTableView];
}


- (void)createTableView
{
    self.table = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, self.listView.bounds.size.height - 40) style:(UITableViewStylePlain)];
    self.table.delegate = self;
    self.table.dataSource = self;
    self.table.backgroundColor = [UIColor clearColor];
    [self.listView addSubview:self.table];

}

#pragma tableView协议方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.tabBarSingle.array.count > 0) {
        return self.tabBarSingle.array.count;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"listtt"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:@"listtt"];
    }
//    cell.textLabel.text = [self.tabBarSingle.array[indexPath.row] name];
    cell.backgroundColor = [UIColor clearColor];
    //取消CELL点击变灰色
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

#pragma tableView高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

#pragma tableView点击
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.tabBarSingle.index = indexPath.row;
    [self updateMusic];
    
}


#pragma mark - 3种播放方法
- (void)dqxhAction
{
    [UIView animateWithDuration:1 animations:^{
        self.cutView.frame = CGRectMake(0, SCREENHEIGHT, SCREENWIDTH, 100);
        [self.buttonCut setImage:[UIImage imageNamed:@"danquxunhuan"] forState:(UIControlStateNormal)];
    }];
    
    self.isCutMusic = 1;
    
    //    [self playStyle];
}
- (void)qxhAction
{
    [UIView animateWithDuration:1 animations:^{
        self.cutView.frame = CGRectMake(0, SCREENHEIGHT, SCREENWIDTH, 100);
        [self.buttonCut setImage:[UIImage imageNamed:@"quanxunhuan"] forState:(UIControlStateNormal)];
    }];
    
    self.isCutMusic = 0;
    
    //    [self playStyle];
}
- (void)sjAction
{
    [UIView animateWithDuration:1 animations:^{
        self.cutView.frame = CGRectMake(0, SCREENHEIGHT, SCREENWIDTH, 100);
        [self.buttonCut setImage:[UIImage imageNamed:@"suijibofang"] forState:(UIControlStateNormal)];
    }];
    
    self.isCutMusic = 2;
    
    //    [self playStyle];
}

#pragma mark - 歌曲播放方式swith case
- (void)playStyle
{
    switch (self.isCutMusic) {
        case 1://单曲
            
            [self updateMusic];
            
            break;
        case 0://顺序
            
            if (self.tabBarSingle.index == self.tabBarSingle.array.count - 1) {
                self.tabBarSingle.index = 0;
            } else {
                self.tabBarSingle.index += 1;
            }
            
            [self updateMusic];
            
            break;
        case 2://随机
            
            self.tabBarSingle.index = arc4random() % self.tabBarSingle.array.count;
            
            [self updateMusic];
            
            break;
            
        default:
            break;
    }
}


#pragma mark - 播放列表关闭
- (void)closeListView
{
    [UIView animateWithDuration:1 animations:^{
        self.listView.frame = CGRectMake(0, SCREENHEIGHT, SCREENWIDTH, SCREENHEIGHT / 2.0);
    }];
    
}


#pragma mark - 播放器按钮方法(播放, 上一曲, 下一曲)
- (void)backplay
{
    if ([NSString stringWithFormat:@"%ld", self.tabBarSingle.index] == nil) {
        
        return;
    }
    //初始为列表循环
    if (self.tabBarSingle.index == 0) {
        self.tabBarSingle.index = self.tabBarSingle.array.count - 1;
    } else {
        self.tabBarSingle.index -= 1;
    }
    
    
    [self updateMusic];
}
#pragma mark - 动画判断
- (void)isplay
{
    self.isplaybool = !self.isplaybool;
    //动画判断值
    if (!self.isplaybool) {
        [self.buttonPlay setImage:[UIImage imageNamed:@"playMusic"] forState:(UIControlStateNormal)];
        [self.tabBarSingle.tabBarView.songStopORStart setImage:[UIImage imageNamed:@"playMusic"] forState:(UIControlStateNormal)];
        [self.tabBarSingle.player pause];
//        self.tabBarSingle.stopAngle = 0;
        self.stopAngle = 0;
        [self startAnimation];
    } else {
        
        [self.buttonPlay setImage:[UIImage imageNamed:@"pause"] forState:(UIControlStateNormal)];
        [self.tabBarSingle.tabBarView.songStopORStart setImage:[UIImage imageNamed:@"pause"] forState:(UIControlStateNormal)];
        [self.tabBarSingle.player resume];

//        self.stopAngle = 1;

        self.stopAngle = 0.5;

//        self.tabBarSingle.stopAngle = 10;
        [self startAnimation];
    }
    
}

- (void)nextplay
{
    
    if ([NSString stringWithFormat:@"%ld", self.tabBarSingle.index] == nil) {
        
        return;
    }
    //初始为列表循环
    if (self.tabBarSingle.index == self.tabBarSingle.array.count - 1) {
        self.tabBarSingle.index = 0;
    } else {
        self.tabBarSingle.index += 1;
    }
    
    [self updateMusic];
    
}
#pragma mark - 更新播放
- (void)updateMusic
{
    NSString *url = self.tabBarSingle.array[self.tabBarSingle.index];
//                      lastObject] objectForKey:@"url"];
    
    
    
    
    [self.tabBarSingle play:url];
    
//    self.headerView.label.text = [self.tabBarSingle.array[self.tabBarSingle.index] name];
//    self.tabBarSingle.tabBarView.songName.text = [self.tabBarSingle.array[self.tabBarSingle.index] name];
//    self.tabBarSingle.tabBarView.songerName.text = [self.tabBarSingle.array[self.tabBarSingle.index] singerName];
//    self.headerView.label.text = [self.tabBarSingle.array[self.tabBarSingle.index] name];
    
//            NSInteger str1 = [[[self.tabBarSingle.array[self.tabBarSingle.index] urlList].firstObject objectForKey:@"duration"] integerValue];
//            self.end.text = [NSString stringWithFormat:@"%.0f:%02ld", str1 / 1000 / 60.0, str1 / 1000 % 60];
    
}

#pragma mark - 动画
- (void)startAnimation
{
    CGAffineTransform endAngle = CGAffineTransformMakeRotation(self.angle * (M_PI / 180.0f));
    
    [UIView animateWithDuration:0.358 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
        self.img.transform = endAngle;
    } completion:^(BOOL finished) {
        if (self.isplaybool) {
            self.angle += self.stopAngle;
            [self startAnimation];
        }
//                NSLog(@"%.f", angle);
    }];
    
}


#pragma mark - 进度条方法 改变播放器进度
- (void)sliderAction:(id)sender
{
    if (self.tabBarSingle.player) {
        UISlider *sliderNew = sender;
        [self.tabBarSingle.player seekToTime:sliderNew.value];
    }
}

#pragma mark - 定时器方法
- (void)timerAction:(id)sender
{
    if (self.slider) {
        //歌曲总时间
        self.slider.maximumValue = self.tabBarSingle.player.duration;
        //滑块当前位置 -> 歌放到的地方
        self.slider.value = self.tabBarSingle.player.progress;
        NSInteger min = (NSInteger)self.tabBarSingle.player.progress / 60;
        
        NSInteger sec = (NSInteger)self.tabBarSingle.player.progress % 60;
        
        //播放结束自动播放下一曲
        if (self.tabBarSingle.player.progress > 0) {
            if (self.tabBarSingle.player.progress > self.tabBarSingle.player.duration - 3) {
                
                [self playStyle];
            }
        }
        
        
        self.start.text = [NSString stringWithFormat:@"%02ld:%02ld", min, sec];
        self.end.text = [NSString stringWithFormat:@"%02ld:%02ld", (NSInteger)self.tabBarSingle.player.duration / 60, (NSInteger)self.tabBarSingle.player.duration % 60];
    }
}


#pragma mark - 选择播放模式
- (void)choose
{
    [UIView animateWithDuration:1 animations:^{
        self.cutView.frame = CGRectMake(0, SCREENHEIGHT - 100, SCREENWIDTH, 100);
    }];
}

#pragma mark - 播放歌曲列表
- (void)musicList
{
    [UIView animateWithDuration:1 animations:^{
        self.listView.frame = CGRectMake(0, SCREENHEIGHT / 2.0, SCREENWIDTH, SCREENHEIGHT / 2.0);
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
